import Api from '@/api/common';
import { setToken, setClientId, getUserName, setUserName, removeToken } from '@/utils/auth';

export default {
  state: {
    token: null,
    roles: [],
    employeeId: null,
    username: '用户'
  },
  mutations: {
    SET_TOKEN (state, token) {
      state.token = token;
    },
    REMOVE_TOKEN (state) {
      state.token = null;
    },
    SET_ROLES (state, roles) {
      state.roles = roles;
    },
    REMOVE_ROLES (state) {
      state.roles = [];
    },
    SET_EMPLOYEE_ID (state, employeeId) {
      state.employeeId = employeeId;
    },
    SET_USER_NAME (state, username) {
      state.username = username;
    }
  },
  actions: {
    setToken ({ commit }, token) {
      commit('SET_TOKEN', token);
    },
    goLogin({ commit }, userInfo) {
      return Api.goLogin(userInfo)
        .then((res) => {
          // 登录成功后将token存储在cookie之中
          const token = res.accessToken.token;
          const clientId = res.clientId;
          setClientId(clientId);
          setToken(token);
          setUserName(userInfo.username);
          commit('SET_TOKEN', token);
          return res;
        }).catch(error => Promise.reject(error));
    },
    goLogout ({ commit }) {
      return new Promise((resolve) => {
        removeToken();
        commit('REMOVE_TOKEN');
        commit('REMOVE_ROLES');
        resolve();
      });
    },
    getUserInfo ({ commit }) {
      const username = getUserName();
      return Api.getUserInfo({ username })
        .then((res) => {
          if (!res.status) {
            commit('SET_ROLES', res.obj.roles);
            commit('SET_EMPLOYEE_ID', res.obj.employeeId);
            commit('SET_USER_NAME', res.obj.name);
          }
          return res.obj;
        }).catch(error => Promise.reject(error));
    }
  }
};
